#include<stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <dirent.h>
#include "logger.h"


#define PATH "/sys/bus/w1/devices/"


int get_temperature (float *t);
/*  int main(int argc,char**argv)
{
	float              temp;
	int                rv=-1;
	rv=temperature(&temp);
	if(rv<0)
	{
		printf("get temperature failure,return:%d\n",rv);
		return -1;
	}

	//printf("temperature=%f\n",temp);

}
*/




int get_temperature (float *t)
{
	int                  fd=-1;
	char                 buf[128] ;
	char                *ptr=NULL;
	char                 w1_path[64]=PATH;
	DIR		    *dirop;
	char                *path_28=NULL;
	struct dirent       *redir=NULL;
	


	dirop=opendir(PATH);
	if(!dirop)
	{
		log_error("open dir %s failure\n",PATH);
		return -1;
	}



	while(NULL!=(redir=readdir(dirop)))
	{
	
         	if((path_28=(strstr(redir->d_name,"28-")))!=NULL)
		{
		     strncat(w1_path,path_28,sizeof(w1_path)-strlen(PATH));
		}
	}

	closedir(dirop);
	//printf("w1_path:%s\n,path_28%s",w1_path,path_28);

	strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));
	//printf("w1_path:%s\n",w1_path);




	fd = open(w1_path,O_RDONLY);
	if (fd<0)
	{
		log_error("open file failure:%s\n",strerror(errno));
		return -2;
	}
	memset(buf,0,sizeof(buf));
	if((read(fd,buf,sizeof(buf)))<0)
	{
		log_error("read file failure:%s\n",strerror(errno));
		return -3;
	}
	//printf("buf=%s\n",buf);
	ptr=(strstr(buf,"t="));
	if(!ptr)
	{
		log_error("Can not found t\n");
	}
	ptr=(ptr+2);
	*t=(atof(ptr))/1000;
	log_debug("temperature=%.2f\n",*t);
	return 0;
	
}
